/*
 * @Descripttion:
 * @Author: xiaodong
 * @Date: 2020-11-23 10:03:07
 * @LastEditTime: 2021-02-01 21:11:05
 * @FilePath: \cloud-monitor-sdk\src\reporter.ts
 */

import { Config } from "./config";
import { queryString, serialize, warn } from "./utils/tools";

// 上报
export function report(e: ReportData) {
  "res" === e.type
    ? send(e)
    : "error" === e.type
    ? send(e)
    : "behavior" === e.type
    ? send(e)
    : "health" === e.type &&
      window &&
      window.navigator &&
      "function" == typeof window.navigator.sendBeacon
    ? sendBeacon(e)
    : send(e);
  return this;
}

// post上报
export function send(msg: ReportData) {
  var body = msg[msg.type];
  delete msg[msg.type];
  var url = `${Config.reportUrl}?${serialize(msg)}`;
  post(url, {
    [msg.type]: body,
  });
  // new Image().src = `${Config.reportUrl}?${serialize(msg)}`
}

export function post(url, body) {
  // // 图片打点
  // const img = new window.Image();
  // img.src = `${url}&body=${encodeURIComponent(JSON.stringify(body))}`;
  var XMLHttpRequest = window.__oXMLHttpRequest_ || window.XMLHttpRequest;
  if (typeof XMLHttpRequest === 'function') {
    try {
      var xhr = new XMLHttpRequest();
      xhr.open("POST", url, !0)
      xhr.setRequestHeader("Content-Type", "text/plain")
      // xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
      xhr.send(JSON.stringify(body))
    } catch (e) {
      warn('[performanceJs] Failed to log, POST请求失败')
    }
  } else {
    warn('[performanceJs] Failed to log, 浏览器不支持XMLHttpRequest')
  }
}
export function get(url, success) {
  // 图片打点
  // const img = new window.Image();
  // img.src = url;
  var XMLHttpRequest = window.__oXMLHttpRequest_ || window.XMLHttpRequest;
  if (typeof XMLHttpRequest === 'function') {
    try {
      var xhr = new XMLHttpRequest();
      xhr.open("head", url, !0)
      // xhr.setRequestHeader("Content-Type", "image/png")
      // xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
      xhr.send()
      xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
          if(xhr.status==200){
            success(xhr.responseText)
          }
        }
      }
    } catch (e) {
      warn('[performanceJs] Failed to log, get请求失败')
    }
  } else {
    warn('[performanceJs] Failed to log, 浏览器不支持XMLHttpRequest')
  }
}
// 健康检查上报
export function sendBeacon(e: any) {
  "object" == typeof e && (e = serialize(e));
  e = `${Config.reportUrl}?${e}`;
  window && window.navigator && "function" == typeof window.navigator.sendBeacon
    ? window.navigator.sendBeacon(e)
    : warn("[arms] navigator.sendBeacon not surported");
}
